package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.ReportVO;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@Service
public class SoulResultApiImpl implements SoulResultApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveAnswers(SoulResult soulResult) {

        List<Answer> answers = soulResult.getAnswers();
        String questionId = answers.get(1).getQuestionId();

        //查询试题对应的问卷
        SoulQuestion soulQuestion = mongoTemplate.findOne(Query.query(Criteria.where("id").is(new ObjectId(questionId))), SoulQuestion.class);
        ObjectId paperId = soulQuestion.getSoulPaperId();

        //查询该用户是否已存在该问卷的测试结果
        SoulResult lastResult = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(soulResult.getUserId())
                .and("paperId").is(paperId)), SoulResult.class);
        if (lastResult != null) {
            //更新
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(lastResult.getId()));
            Update update = new Update();
            update.set("answers", answers).set("created", System.currentTimeMillis())
                    .set("score", soulResult.getScore()).set("reportId", soulResult.getReportId());
            mongoTemplate.updateFirst(query, update, SoulResult.class);

        } else {
            //新增
            soulResult.setPaperId(paperId);
            soulResult.setCreated(System.currentTimeMillis());
            soulResult.setId(new ObjectId());
            mongoTemplate.insert(soulResult);
        }
        return soulResult.getReportId().toHexString();
    }

    @Override
    public int findScoreByOption(List<ObjectId> optionIds) {
        int score = 0;
        for (ObjectId optionId : optionIds) {
            SoulQuestionOption option = mongoTemplate.findOne(Query.query(Criteria.where("id").is(optionId)), SoulQuestionOption.class);
            score += option.getScore();
        }
        return score;
    }

}
